#include "guiterm.hpp"

CommandPrompt::CommandPrompt(Session *session, QWidget *parent)
	:ViewSegment(session, parent)
{
	this->session = session;
	this->history = new CommandHistory();
	
	QLayout *layout = new QHBoxLayout();
	layout->setSpacing(0);
	layout->setContentsMargins(0,0,0,0);
	setLayout(layout);
	
	prompt = new QLabel(QString(session->getPromptText().c_str()), this);
	prompt->setPalette(*PaletteManager::activePrompt());
	prompt->setFont(config.font);
	layout->addWidget(prompt);
	
	inputBox = new CommandPromptEdit(this);
	layout->addWidget(inputBox);
	QObject::connect(inputBox, SIGNAL(returnPressed()), this, SLOT(onEnter()));
	
	setFocusPolicy(Qt::ClickFocus);
	inputBox->setFocusPolicy(Qt::ClickFocus);
	setFocusProxy(inputBox);
}

CommandPrompt::~CommandPrompt()
{
}

void CommandPrompt::setPromptText(string promptText)
{
	prompt->setText(promptText.c_str());
}

void CommandPrompt::reset()
{
	prompt->setText(QString(session->getPromptText().c_str()));
	inputBox->setText("");
}

void CommandPrompt::onEnter()
{
	history->commit(inputBox->text().toStdString());
	session->typedCommand(inputBox->text().toStdString());
}

QWidget *CommandPrompt::frozenPrompt()
{
	QString text = prompt->text() + inputBox->text();
	QLabel *ret = new QLabel(text, NULL);
	ret->setPalette(*PaletteManager::inactivePrompt());
	ret->setFont(config.font);
	return ret;
}

void CommandPrompt::focus()
{
	inputBox->setFocus();
}

void CommandPrompt::setCommand(string cmd, bool highlight)
{
	inputBox->setText(cmd.c_str());
	
	if(highlight)
		inputBox->selectAll();
	else
		inputBox->end(false);
}

void CommandPrompt::tabComplete()
{
	string text = inputBox->text().toStdString();
	int cursorPos = inputBox->cursorPosition();
	string prefix = text.substr(0, cursorPos);
	string suffix = text.substr(cursorPos, text.length()-cursorPos);
	
	RPCParams tabCompleteParams;
		tabCompleteParams.set("prefix", prefix);
		tabCompleteParams.set("suffix", suffix);
	session->getHost()->call("rtabcomp", &tabCompleteParams);
}

void CommandPrompt::tabCompletionReceived(string prefix, string suffix)
{
	string fullText = prefix+suffix;
	inputBox->setText(fullText.c_str());
	inputBox->setCursorPosition(prefix.length());
}

void CommandPrompt::setSelectedFiles(vector<string> fileNames)
{
	// Replace selected text, rather than adding to it
	if(inputBox->selectionStart() >= 0)
		inputBox->backspace();
	
	QString newText = "";
	
	for(unsigned ii=0; ii<fileNames.size(); ii++)
	{
		if(ii)
			newText += " ";
		newText += QString(quoteProtectString(fileNames[ii].c_str()).c_str());
	}
	
	int cursorPos = inputBox->cursorPosition();
	inputBox->insert(newText);
	inputBox->setSelection(cursorPos, newText.length());
}

